package com.unlcn.ils.wms.api.activemq;

import cn.huiyunche.commons.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.unlcn.ils.wms.backend.enums.WhCodeEnum;
import com.unlcn.ils.wms.backend.service.outbound.WmsShipmentPlanService;
import com.unlcn.ils.wms.base.model.stock.WmsShipmentPlan;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 从TMS获取订单数据
 * Created by DELL on 2017/8/30.
 */
public class GetOrderByQueue implements MessageListener {

    private Logger logger = LoggerFactory.getLogger(GetOrderByQueue.class);

    @Autowired
    private WmsShipmentPlanService wmsShipmentPlanService;

    @Override
    public void onMessage(Message message) {
        String order = "";
        if (message instanceof BytesMessage) {
            BytesMessage bm = (BytesMessage) message;
            byte[] bys;
            try {
                bys = new byte[(int) bm.getBodyLength()];
                bm.readBytes(bys);
                order = new String(bys);
            } catch (JMSException e) {
                logger.error("GetOrderByQueue.onMessage：TMS传送订单数据异常");
            }
        } else if (message instanceof TextMessage) {
            TextMessage bm = (TextMessage) message;

            try {
                order = bm.getText();
            } catch (JMSException e) {
                logger.error("GetOrderByQueue.onMessage：TMS传送订单数据异常");
            }
        } else if (message instanceof MapMessage) {
            MapMessage map = (MapMessage) message;
            try {
                order = map.getString("id") + map.getString("name");
            } catch (JMSException e) {
                logger.error("GetOrderByQueue.onMessage：TMS传送订单数据异常");
            }
        }
        //打印日志
        logger.info("GetOrderByQueue.onMessage insertMqToLog 收到MQ推送消息=========", order);
        /*
          PICK-提货任务-------------10
          DISTRIBUTION-配送任务,----20
          TRUNK-干线任务,-----------30
          TRANSFER-移库任务,--------40
          DRAYAGE-短驳任务----------50
         */
        String finalOrder = order;
        new Thread(() -> {
            try {
                wmsShipmentPlanService.insertMqToLogNew(finalOrder);
            } catch (Exception e) {
                logger.error("GetOrderByQueue.onMessage insertMqToLog", e.getMessage());
            }
        }).start();
        JSONObject object = JSON.parseObject(order);
        String shipno = object.getString("shipno");  //指令号
        String supplier = object.getString("supplier");
        String vehicle = object.getString("vehicle");//板车牌号
        String timestamp = object.getString("timeStamp");//用于解决mq乱序的时间戳
        //指令肯定是必须的
        if (StringUtils.isNotBlank(shipno)) {
            List<WmsShipQueueDetailDTO> wmsShipQueueDTOList = JSON.parseArray(object.getString("route"), WmsShipQueueDetailDTO.class);//获取json对象数组格式
            if (StringUtils.isBlank(timestamp)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                timestamp = sdf.format(new Date());
            }
            List<WmsShipmentPlan> wmsShipmentPlanList = null;
            if (CollectionUtils.isNotEmpty(wmsShipQueueDTOList)
                    && wmsShipQueueDTOList.size() > 0) {
                wmsShipmentPlanList = generateWmsShipmentPlanNew(shipno, supplier, vehicle, wmsShipQueueDTOList);
            }
            //  现在mq要实现新增发运计划的话 需要判断仓库是否是重庆前置库 是才进行消费  --已确定只推更新的数据s
            try {
                wmsShipmentPlanService.updateShipmentPlanByInfoNew(wmsShipmentPlanList, shipno, timestamp);
            } catch (BusinessException e) {
                logger.error("WmsShipmentPlanServiceImpl.updateShipmentPlanByInfoNew BusinessException:", e);
            } catch (Exception ex) {
                logger.error("WmsShipmentPlanServiceImpl.updateShipmentPlanByInfoNew error:", ex);
            }
        }
    }


    /**
     * 增加按照起始地过滤消息
     *
     * @param shipno                 发运
     * @param supplier               承运商
     * @param vehicle                板车号
     * @param wmsShipQueueDetailDTOS 参数对象
     * @return 返回值
     */
    private List<WmsShipmentPlan> generateWmsShipmentPlanNew(String shipno,
                                                             String supplier,
                                                             String vehicle,
                                                             List<WmsShipQueueDetailDTO> wmsShipQueueDetailDTOS) {
        List<WmsShipmentPlan> wmsShipmentPlanList = Lists.newArrayList();
        for (WmsShipQueueDetailDTO wmsShipQueueDetailDTO : wmsShipQueueDetailDTOS) {
            //过滤掉起始地非重庆前置库的数据
            if (StringUtils.isNotBlank(wmsShipQueueDetailDTO.getOrigin())
                    && WhCodeEnum.UNLCN_XN_CQ.getText().equals(wmsShipQueueDetailDTO.getOrigin())) {
                WmsShipmentPlan wmsShipmentPlan = new WmsShipmentPlan();
                wmsShipmentPlan.setSpDispatchNo(shipno);//调度指令号
                wmsShipmentPlan.setSpCarrier(supplier);//分供方名称
                wmsShipmentPlan.setSpSupplierVehiclePlate(vehicle);//板车牌号
                wmsShipmentPlan.setSpWaybillNo(wmsShipQueueDetailDTO.getCustshipno());//客户运单号
                wmsShipmentPlan.setSpOrderNo(wmsShipQueueDetailDTO.getOrderno());//系统订单号
                wmsShipmentPlan.setSpVin(wmsShipQueueDetailDTO.getVin());//货物底盘号
                wmsShipmentPlan.setSpVehicleName(wmsShipQueueDetailDTO.getStyle());//货物车型
                wmsShipmentPlan.setSpVehicleDesc(wmsShipQueueDetailDTO.getStyleDesc());//货物描述
                wmsShipmentPlan.setSpOrigin(wmsShipQueueDetailDTO.getOrigin());//起运地
                wmsShipmentPlan.setSpDest(wmsShipQueueDetailDTO.getDest());//客户货运地
                wmsShipmentPlan.setSpCustomerName(wmsShipQueueDetailDTO.getCustomer());//客户名称
                wmsShipmentPlan.setSpRouteEnd(wmsShipQueueDetailDTO.getRoute_end());
                wmsShipmentPlan.setSpEstimateLoadingTime(new Date());//当前时间为计划装车时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (StringUtils.isNotBlank(wmsShipQueueDetailDTO.getDtship())) {
                    try {
                        wmsShipmentPlan.setSpDtship(sdf.parse(wmsShipQueueDetailDTO.getDtship()));//设置调度时间
                    } catch (ParseException e) {
                        logger.error("GetOrderByQueue.generateWmsShipmentPlan error : ", e);
                        throw new BusinessException("日期转换异常!");
                    }
                }
                wmsShipmentPlanList.add(wmsShipmentPlan);
            }
        }
        return wmsShipmentPlanList;
    }

    //public static void main(String[] args) {
    //    String json = "{\n" +
    //            "    \"route\":[\n" +
    //            "        {\n" +
    //            "            \"styleDesc\":\"14款蓝色凯运双排2800轴距后双胎\",\n" +
    //            "            \"orderno\":\"0170908573\",\n" +
    //            "            \"route_end\":\"东莞\",\n" +
    //            "            \"origin\":\"南昌\",\n" +
    //            "            \"vin\":\"LEFAFCC28GHN30005\",\n" +
    //            "            \"style\":\"14款凯运窄体双长车\",\n" +
    //            "            \"dest\":\"东莞\",\n" +
    //            "            \"custshipno\":\"0170908573\",\n" +
    //            "            \"customer\":\"江铃股份\"\n" +
    //            "        },\n" +
    //            "        {\n" +
    //            "            \"styleDesc\":\"宝典新超值版2016MY柴油国四两驱舒适款墨绿色X号厢\",\n" +
    //            "            \"orderno\":\"0170980570\",\n" +
    //            "            \"route_end\":\"从化\",\n" +
    //            "            \"origin\":\"南昌\",\n" +
    //            "            \"vin\":\"LEFADCG17GHP23852\",\n" +
    //            "            \"style\":\"匹卡v柴\",\n" +
    //            "            \"dest\":\"从化\",\n" +
    //            "            \"custshipno\":\"0170980570\",\n" +
    //            "            \"customer\":\"江铃股份\"\n" +
    //            "        }\n" +
    //            "    ],\n" +
    //            "    \"shipno\":\"Z170906344\",\n" +
    //            "    \"supplier\":\"S1606010208\",\n" +
    //            "    \"vehicle\":\"粤A90915\"\n" +
    //            "}";
    //
    //
    //}
}
